/*
 Copyright 2012 Sven-Ove Bjerkan

 This file is part of KO-Ozi.

 KO-Ozi is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 KO-Ozi is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with KO-Ozi. If not, see <http://www.gnu.org/licenses/>.
 */
package com.koozi.auto;

import com.koozi.FileFolder;
import com.koozi.diff_match_patch;
import com.oziexplorer.OziAPI;
import com.oziexplorer.OziException;
import com.oziexplorer.WaypointFile;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 * This class handles the "sekundær"-functionality
 *
 * @author Sven-Ove Bjerkan
 */
public class OziAutoload extends OziAuto implements Runnable {

    public OziAutoload(javax.swing.JLabel lblLastupdate) {
        super(lblLastupdate);
    }

    // to run in another thread
    @Override
    public void run() {
        try {
            // Always try to create projectfolder
            if (!createProjectfolder()) {
                System.err.println("Kunne ikke opprette mappe!");
            }
            File f = null;
            WaypointFile wpFile = new WaypointFile();
            diff_match_patch dmp = new diff_match_patch();
            while (true) {
                if (!OziAPI.findOzi()) {
                    JOptionPane.showMessageDialog(null, "OziExplorer kjører ikke!",
                            "Feilmelding", JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                }

                // Read WP and does the file with WP exist?
                f = new File(folderpath + "WP.wpt");
                if (f.exists() && f.canRead()) {
                    // Save existing waypoints to a tempfile
                    f = File.createTempFile("koozi", ".wpt");
                    f.deleteOnExit();
                    OziAPI.saveWaypointFile(f.getAbsolutePath());

                    // Compare the tempfile with the last saved WP-file
                    String tmpWP = FileFolder.fileToString(f.getAbsolutePath());
                    String oldWP = FileFolder.fileToString(folderpath + "WP.wpt");

                    LinkedList<diff_match_patch.Diff> diff = dmp.diff_main(tmpWP, oldWP, true);

                    // The WP-list is changed, so load it! :)
                    if (diff.size() != 1) {
                        OziAPI.clearWaypoints();
                        wpFile.read(folderpath + "WP.wpt");
                        wpFile.display();
                        OziAPI.saveWaypointFlag(true);
                    }
                    f = null;
                }

                // Read tracks
                for (int i = 2; i <= settings.getSaveTracks(); i++) {
                    f = new File(folderpath + i + ".plt");
                    // Check that the file exists
                    if (f.exists() && f.canRead()) {
                        // Check if the track has changed
                        f = File.createTempFile("koozi", ".plt");
                        f.deleteOnExit();
                        OziAPI.saveTrackFile(i, f.getAbsolutePath());
                        String tmpPLT = FileFolder.fileToString(f.getAbsolutePath());
                        String oldPLT = FileFolder.fileToString(folderpath + i + ".plt");
                        LinkedList<diff_match_patch.Diff> diff = dmp.diff_main(tmpPLT, oldPLT, true);
                        // The track is changed, so load! :)
                        if (diff.size() != 1) {
                            OziAPI.loadTrackFile(i, folderpath + i + ".plt");
                        }
                    }
                    f = null;
                }

                /*
                String[] trackFiles = settings.getListOfFiles(settings.getProjectPath(), "plt");
                for (int i = 0; i < trackFiles.length; i++) {
                    int fileName = Integer.parseInt(trackFiles[i].substring(0, trackFiles[i].length() - 4));
                    if (fileName < 50) {
                        continue;
                    }

                    System.out.println("F: " + fileName);

                    f = new File(folderpath + i + ".plt");
                    // Check that the file exists
                    if (f.exists() && f.canRead()) {
                        OziAPI.loadTrackFile(i, folderpath + i + ".plt");
                    }
                    f = null;
                }
*/
                // Set the time of last update
                cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1"));
                lblLastupdate.setText(dateFormat.format(cal.getTime()));

                // Sleep for the given interval
                Thread.sleep((int) ((Double) settings.getOpenSaveInterval() * 60 * 1000));

            }
        } catch (IOException ex) {
            Logger.getLogger(OziAutoload.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OziException ex) {
            Logger.getLogger(OziAutosave.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
        }
    }
}
